import React from 'react';
import { Link } from 'react-router-dom';
import { Menu } from 'antd';
import Icon from '@ant-design/icons';
import { checkPermission } from 'permission/Index';
import { getStore } from 'store/store';

const { SubMenu } = Menu;

/**功能：根据菜单配置，生成左侧菜单*/
export default function getSiderBarMenu(siderBarConfig) {
  // 渲染图标
  function renderIcon(icon) {
    if (!icon) {
      return <></>;
    }
    return <Icon component={icon} />;
  }
  // 渲染子级菜单
  function renderMenuItem(item) {
    const store = getStore();
    if (!store.get('firstMenu').path) {
      // 第一个有权限的子级菜单
      store.set('firstMenu', item);
      store.save();
    }
    return (
      <Menu.Item key={item.path} icon={renderIcon(item.icon)}>
        <Link to={item.path}>{item.name}</Link>
      </Menu.Item>
    );
  }
  // 渲染父级菜单
  function renderSubMenu(item) {
    return (
      <SubMenu key={item.path} icon={renderIcon(item.icon)} title={<span>{item.name}</span>}>
        {renderMenu(item.children)}
      </SubMenu>
    );
  }
  // 渲染菜单
  function renderMenu(menu) {
    return menu.map(item => {
      // item.hidden = item.hidden || !checkPermission(item.path);
      // 1.没有权限-不显示
      if (item.hidden) return null;
      // 2.有权限-显示
      return item.children ? renderSubMenu(item) : renderMenuItem(item);
    });
  }

  return renderMenu(siderBarConfig);
}
